package com.xjrsoft.module.oa.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xjrsoft.common.Enum.DeleteMarkEnum;
import com.xjrsoft.core.secure.utils.SecureUtil;
import com.xjrsoft.core.tool.utils.BeanUtil;
import com.xjrsoft.module.base.entity.XjrBaseUser;
import com.xjrsoft.module.base.utils.OrganizationCacheUtil;
import com.xjrsoft.module.oa.entity.XjrOaMessage;
import com.xjrsoft.module.oa.entity.XjrOaNews;
import com.xjrsoft.module.oa.mapper.XjrOaMessageMapper;
import com.xjrsoft.module.oa.service.IXjrOaMessageService;
import com.xjrsoft.module.oa.service.IXjrOaMessagestatusService;
import com.xjrsoft.module.oa.service.IXjrOaNewsService;
import com.xjrsoft.module.oa.vo.MessageListVo;
import com.xjrsoft.module.oa.vo.MessageVo;
import com.xjrsoft.module.oa.vo.NewsVo;
import com.xjrsoft.module.oa.vo.workflowInfoVo;
import com.xjrsoft.module.workflow.mapper.NwfTaskMapper;
import com.xjrsoft.module.workflow.vo.TaskVo;
import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zwq
 * @since 2021-05-18
 */
@Service
public class XjrOaMessageServiceImpl extends ServiceImpl<XjrOaMessageMapper, XjrOaMessage> implements IXjrOaMessageService {

@Autowired
private XjrOaMessageMapper xjrOaMessageMapper;

@Autowired
private IXjrOaMessagestatusService iXjrOaMessagestatusService;

@Autowired
private NwfTaskMapper nwfTaskMapper;

@Autowired
private IXjrOaNewsService iXjrOaNewsService;

@Autowired
private HistoryService historyService;

    
    @Override
    public List<MessageListVo> getList() {
        List<XjrBaseUser> xjrBaseUserList = OrganizationCacheUtil.getListCaches(OrganizationCacheUtil.USER_LIST_CACHE_KEY);
        String userId = SecureUtil.getUserId();
        ArrayList<MessageListVo> messageListVos = new ArrayList<>();
        //获取新闻类的消息
        List<Integer> newModules = new ArrayList<>();
        newModules.add(10);
        List<MessageVo> newMeassageVoList = xjrOaMessageMapper.getMeassageList(userId,newModules,10,null);
        List<String> messageLinks = newMeassageVoList.stream().map(MessageVo::getLink).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(messageLinks)) {
            List<XjrOaNews> xjrOaNewsList = iXjrOaNewsService.listByIds(messageLinks);
            for (MessageVo messageVo : newMeassageVoList) {
                //添加新闻或通知
                Optional<XjrOaNews> xjrOaNewsOptional = xjrOaNewsList.stream().filter(x -> x.getNewsId().equals(messageVo.getLink())).findFirst();
                if (xjrOaNewsOptional.isPresent()) {
                    messageVo.setNewsVo(BeanUtil.copy(xjrOaNewsOptional.get(), NewsVo.class));
                }
            }
        }
        //获取新闻类未读消息个数
        Integer  newMeassageUnreadCount= xjrOaMessageMapper.getMeassageUnreadCount(userId,newModules);
        MessageListVo newmessageListVo = new MessageListVo();
        newmessageListVo.setName("新闻");
        newmessageListVo.setUnread(newMeassageUnreadCount);
        newmessageListVo.setMessageList(newMeassageVoList);
        messageListVos.add(newmessageListVo);
        
        //获取公告类的消息
        List<Integer> informModules = new ArrayList<>();
        informModules.add(11);
        List<MessageVo> informMeassageVoList = xjrOaMessageMapper.getMeassageList(userId,informModules,10,null);
        List<String> informMeassageLinkList = informMeassageVoList.stream().map(MessageVo::getLink).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(informMeassageLinkList)) {
            List<XjrOaNews> xjrOaNewsList1 = iXjrOaNewsService.listByIds(informMeassageLinkList);
            for (MessageVo messageVo : informMeassageVoList) {
                //添加新闻或通知
                Optional<XjrOaNews> xjrOaNewsOptional = xjrOaNewsList1.stream().filter(x -> x.getNewsId().equals(messageVo.getLink())).findFirst();
                if (xjrOaNewsOptional.isPresent()) {
                    messageVo.setNewsVo(BeanUtil.copy(xjrOaNewsOptional.get(), NewsVo.class));
                }
            }
        }
        Integer  informMeassageUnreadCount= xjrOaMessageMapper.getMeassageUnreadCount(userId,informModules);
        MessageListVo informmessageListVo = new MessageListVo();
        informmessageListVo.setName("公告");
        informmessageListVo.setUnread(informMeassageUnreadCount);
        informmessageListVo.setMessageList(informMeassageVoList);
        messageListVos.add(informmessageListVo);
        
        //获取日程类的消息
        List<MessageVo> scheduleMeassageVoList = xjrOaMessageMapper.getScheduleMeassageList(userId,12,10,null);
        Integer  scheduleMeassageUnreadCount= xjrOaMessageMapper.getScheduleMeassageUnreadCount(userId,12);
        MessageListVo schedulemessageListVo = new MessageListVo();
        schedulemessageListVo.setName("日程");
        schedulemessageListVo.setUnread(scheduleMeassageUnreadCount);
        schedulemessageListVo.setMessageList(scheduleMeassageVoList);
        messageListVos.add(schedulemessageListVo);
        
        //获取流程审批类的消息
        List<Integer> approvalModules = new ArrayList<>();
        approvalModules.add(13);
        approvalModules.add(16);
        List<MessageVo> approvalMeassageVoList = xjrOaMessageMapper.getMeassageList(userId,approvalModules,5,null);
        Integer  approvalMeassageUnreadCount= xjrOaMessageMapper.getMeassageUnreadCount(userId,approvalModules);
        List<String> taskIds = approvalMeassageVoList.stream().map(s -> s.getLink().split(";")[0]).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(taskIds)) {
            List<TaskVo> taskVoList = nwfTaskMapper.getTaskByRunTask(taskIds);
            approvalMeassageVoList.forEach(messageVo -> {
                String link = messageVo.getLink();
                String[] split = link.split(";");
                workflowInfoVo workflowInfoVo = new workflowInfoVo();
                //查看任务状态
                Optional<TaskVo> optionalTask = taskVoList.stream().filter(x -> x.getTaskId().equals(split[0])).findFirst();
                Optional<XjrBaseUser> baseUserOptional = xjrBaseUserList.stream().filter(s -> s.getUserId().equals(split[5])).findFirst();
                workflowInfoVo.setTaskId(split[0]==null?"":split[0]).setTaskName(split[1]==null?"":split[1]).setSchemeName(split[2]==null?"":split[2]).setProcessInstanceId(split[3]).setCreateTime(split[4]).setStartUser(baseUserOptional.isPresent()?baseUserOptional.get().getRealName():"");
                if (!optionalTask.isPresent()) {
                    workflowInfoVo.setTaskStatus("1");
                } else {
                    workflowInfoVo.setTaskStatus("0");
                }
                String processInstanceId = workflowInfoVo.getProcessInstanceId();
                HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
                if(historicProcessInstance!=null){
                    workflowInfoVo.setDeploymentId(historicProcessInstance.getDeploymentId());
                }
                messageVo.setWorkflowInfoVo(workflowInfoVo);
            });
        }
        MessageListVo approvalmessageListVo = new MessageListVo();
        approvalmessageListVo.setName("流程审批");
        approvalmessageListVo.setUnread(approvalMeassageUnreadCount);
        approvalmessageListVo.setMessageList(approvalMeassageVoList);
        messageListVos.add(approvalmessageListVo);

        //获取流程传阅类的消息
        List<Integer> circulateModules = new ArrayList<>();
        circulateModules.add(14);
        List<MessageVo> circulateMeassageVoList = xjrOaMessageMapper.getMeassageList(userId,circulateModules,5,null);
        Integer  circulateMeassageUnreadCount= xjrOaMessageMapper.getMeassageUnreadCount(userId,circulateModules);
        circulateMeassageVoList.forEach(messageVo -> {
            String link = messageVo.getLink();
            String[] split = link.split(";");
            workflowInfoVo workflowInfoVo = new workflowInfoVo();
            Optional<XjrBaseUser> baseUserOptional = xjrBaseUserList.stream().filter(s -> s.getUserId().equals(split[5])).findFirst();
            workflowInfoVo.setTaskId(split[0]==null?"":split[0]).setTaskName(split[1]==null?"":split[1]).setSchemeName(split[2]==null?"":split[2]).setProcessInstanceId(split[3]).setCreateTime(split[4]).setStartUser(baseUserOptional.isPresent()?baseUserOptional.get().getRealName():"");
            String processInstanceId = workflowInfoVo.getProcessInstanceId();
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
            if(historicProcessInstance!=null){
                workflowInfoVo.setDeploymentId(historicProcessInstance.getDeploymentId());
            }
            messageVo.setWorkflowInfoVo(workflowInfoVo);
        });
        MessageListVo circulatemessageListVo = new MessageListVo();
        circulatemessageListVo.setName("流程传阅");
        circulatemessageListVo.setUnread(circulateMeassageUnreadCount);
        circulatemessageListVo.setMessageList(circulateMeassageVoList);
        messageListVos.add(circulatemessageListVo);
        return messageListVos;
    }

    //删除新闻公告类消息
    @Override
    public boolean deleteNewsMessage(String newsId) {
        List<XjrOaMessage> xjrOaMessageList = list(Wrappers.<XjrOaMessage>query().lambda().eq(XjrOaMessage::getLink, newsId).eq(XjrOaMessage::getDeleteMark, DeleteMarkEnum.NODELETE.getCode()));
        List<String> messageIds = xjrOaMessageList.stream().map(XjrOaMessage::getId).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(messageIds)){
            return true;
        }
        boolean b= iXjrOaMessagestatusService.deleteMessagestatusByIds(messageIds);
        boolean a= this.removeByIds(messageIds);
        return a&&b;
    }
}
